<?php

namespace app\redis\api;

use yii\redis\ActiveRecord;

/**
 * Class Attack
 * @package app\redis\api
 *
 * @property string $api
 * @property string $ip
 * @property int $timestamp
 * @property int $id
 */
class Attack extends ActiveRecord
{
    public static function primaryKey()
    {
        return ['id'];
    }

    public function attributes()
    {
        return ['id', 'ip', 'api', 'timestamp'];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {

            // clear expired
            self::deleteAll(['<=', 'timestamp', time() - 60]);

            return true;
        }

        return false;
    }

    public static function isAttack($ip, $api)
    {
        $count = self::find()
            ->where(['ip' => $ip])
            ->andWhere(['api' => $api])
            // ->andWhere(['>=', 'timestamp', time() - 60])
            ->count();

        // > 5 / minutes
        if ($count > 5) {
            return true;
        }

        return false;
    }
}